home *** CD-ROM | disk | FTP | other *** search
/ Windows Expert / Windows Expert.iso / windownt / tusrc.zip / SRC / SORT.C < prev    next >
C/C++ Source or Header  |  1993-10-02  |  43KB  |  1,780 lines

  1. /* sort - sort lines of text (with all kinds of options).
  2.    Copyright (C) 1988, 1991 Free Software Foundation
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17.  
  18.    Written December 1988 by Mike Haertel.
  19.    The author may be reached (Email) at the address mike@gnu.ai.mit.edu,
  20.    or (US mail) as Mike Haertel c/o Free Software Foundation. */
  21.  
  22. /* Get isblank from GNU libc.  */
  23. #define _GNU_SOURCE
  24.  
  25. #define SIGHUP      SIGTERM
  26. #define SIGPIPE     99
  27. #define SIGQUIT     SIGTERM
  28.  
  29. #include <sys/types.h>
  30. #include <signal.h>
  31. #include <stdio.h>
  32. #include <process.h>
  33. #include "system.h"
  34. #ifdef _POSIX_VERSION
  35. #include <limits.h>
  36. #else
  37. #ifndef UCHAR_MAX
  38. #define UCHAR_MAX 255
  39. #endif
  40. #endif
  41. #ifndef STDC_HEADERS
  42. char *malloc ();
  43. char *realloc ();
  44. void free ();
  45. #endif
  46.  
  47. void error ();
  48. static void usage ();
  49.  
  50. // #define min(a, b) ((a) < (b) ? (a) : (b))
  51. #define UCHAR_LIM (UCHAR_MAX + 1)
  52. #define UCHAR(c) ((unsigned char) (c))
  53.  
  54. /* The kind of blanks for '-b' to skip in various options. */
  55. enum blanktype { bl_start, bl_end, bl_both };
  56.  
  57. /* The name this program was run with. */
  58. char *program_name;
  59.  
  60. /* Table of digits. */
  61. static int digits[UCHAR_LIM];
  62.  
  63. /* Table of white space. */
  64. static int blanks[UCHAR_LIM];
  65.  
  66. /* Table of non-printing characters. */
  67. static int nonprinting[UCHAR_LIM];
  68.  
  69. /* Table of non-dictionary characters (not letters, digits, or blanks). */
  70. static int nondictionary[UCHAR_LIM];
  71.  
  72. /* Translation table folding lower case to upper. */
  73. static char fold_toupper[UCHAR_LIM];
  74.  
  75. /* Table mapping 3-letter month names to integers.
  76.    Alphabetic order allows binary search. */
  77. static struct month
  78. {
  79.   char *name;
  80.   int val;
  81. } const monthtab[] =
  82. {
  83.   {"APR", 4},
  84.   {"AUG", 8},
  85.   {"DEC", 12},
  86.   {"FEB", 2},
  87.   {"JAN", 1},
  88.   {"JUL", 7},
  89.   {"JUN", 6},
  90.   {"MAR", 3},
  91.   {"MAY", 5},
  92.   {"NOV", 11},
  93.   {"OCT", 10},
  94.   {"SEP", 9}
  95. };
  96.  
  97. /* During the merge phase, the number of files to merge at once. */
  98. #define NMERGE 16
  99.  
  100. /* Initial buffer size for in core sorting.  Will not grow unless a
  101.    line longer than this is seen. */
  102. static int sortalloc =  524288;
  103.  
  104. /* Initial buffer size for in core merge buffers.  Bear in mind that
  105.    up to NMERGE * mergealloc bytes may be allocated for merge buffers. */
  106. static int mergealloc =  16384;
  107.  
  108. /* Guess of average line length. */
  109. static int linelength = 30;
  110.  
  111. /* Maximum number of elements for the array(s) of struct line's, in bytes.  */
  112. #define LINEALLOC 262144
  113.  
  114. /* Prefix for temporary file names. */
  115. static char *temp_file_prefix;
  116.  
  117. /* Flag to reverse the order of all comparisons. */
  118. static int reverse;
  119.  
  120. /* Flag for stable sort.  This turns off the last ditch bytewise
  121.    comparison of lines, and instead leaves lines in the same order
  122.    they were read if all keys compare equal.  */
  123. static int stable;
  124.  
  125. /* Tab character separating fields.  If NUL, then fields are separated
  126.    by the empty string between a non-whitespace character and a whitespace
  127.    character. */
  128. static char tab;
  129.  
  130. /* Flag to remove consecutive duplicate lines from the output.
  131.    Only the last of a sequence of equal lines will be output. */
  132. static int unique;
  133.  
  134. /* Nonzero if any of the input files are the standard input. */
  135. static int have_read_stdin;
  136.  
  137. /* Lines are held in core as counted strings. */
  138. struct line
  139. {
  140.   char *text;            /* Text of the line. */
  141.   int length;            /* Length not including final newline. */
  142.   char *keybeg;            /* Start of first key. */
  143.   char *keylim;            /* Limit of first key. */
  144. };
  145.  
  146. /* Arrays of lines. */
  147. struct lines
  148. {
  149.   struct line *lines;        /* Dynamically allocated array of lines. */
  150.   int used;            /* Number of slots used. */
  151.   int alloc;            /* Number of slots allocated. */
  152.   int limit;            /* Max number of slots to allocate.  */
  153. };
  154.  
  155. /* Input buffers. */
  156. struct buffer
  157. {
  158.   char *buf;            /* Dynamically allocated buffer. */
  159.   int used;            /* Number of bytes used. */
  160.   int alloc;            /* Number of bytes allocated. */
  161.   int left;            /* Number of bytes left after line parsing. */
  162. };
  163.  
  164. /* Lists of key field comparisons to be tried. */
  165. static struct keyfield
  166. {
  167.   int sword;            /* Zero-origin 'word' to start at. */
  168.   int schar;            /* Additional characters to skip. */
  169.   int skipsblanks;        /* Skip leading white space at start. */
  170.   int eword;            /* Zero-origin first word after field. */
  171.   int echar;            /* Additional characters in field. */
  172.   int skipeblanks;        /* Skip trailing white space at finish. */
  173.   int *ignore;            /* Boolean array of characters to ignore. */
  174.   char *translate;        /* Translation applied to characters. */
  175.   int numeric;            /* Flag for numeric comparison. */
  176.   int month;            /* Flag for comparison by month name. */
  177.   int reverse;            /* Reverse the sense of comparison. */
  178.   struct keyfield *next;    /* Next keyfield to try. */
  179. } keyhead;
  180.  
  181. /* The list of temporary files. */
  182. static struct tempnode
  183. {
  184.   char *name;
  185.   struct tempnode *next;
  186. } temphead;
  187.  
  188. /* Clean up any remaining temporary files. */
  189.  
  190. static void
  191. cleanup ()
  192. {
  193.   struct tempnode *node;
  194.  
  195.   for (node = temphead.next; node; node = node->next)
  196.     unlink (node->name);
  197. }
  198.  
  199. /* Allocate N bytes of memory dynamically, with error checking.  */
  200.  
  201. char *
  202. xmalloc (n)
  203.      unsigned n;
  204. {
  205.   char *p;
  206.  
  207.   p = malloc (n);
  208.   if (p == 0)
  209.     {
  210.       error (0, 0, "virtual memory exhausted");
  211.       cleanup ();
  212.       exit (2);
  213.     }
  214.   return p;
  215. }
  216.  
  217. /* Change the size of an allocated block of memory P to N bytes,
  218.    with error checking.
  219.    If P is NULL, run xmalloc.
  220.    If N is 0, run free and return NULL.  */
  221.  
  222. char *
  223. xrealloc (p, n)
  224.      char *p;
  225.      unsigned n;
  226. {
  227.   if (p == 0)
  228.     return xmalloc (n);
  229.   if (n == 0)
  230.     {
  231.       free (p);
  232.       return 0;
  233.     }
  234.   p = realloc (p, n);
  235.   if (p == 0)
  236.     {
  237.       error (0, 0, "virtual memory exhausted");
  238.       cleanup ();
  239.       exit (2);
  240.     }
  241.   return p;
  242. }
  243.  
  244. static FILE *
  245. xfopen (file, how)
  246.      char *file, *how;
  247. {
  248.   FILE *fp = strcmp (file, "-") ? fopen (file, how) : stdin;
  249.  
  250.   if (fp == 0)
  251.     {
  252.       error (0, errno, "%s", file);
  253.       cleanup ();
  254.       exit (2);
  255.     }
  256.   if (fp == stdin)
  257.     have_read_stdin = 1;
  258.   return fp;
  259. }
  260.  
  261. static void
  262. xfclose (fp)
  263.      FILE *fp;
  264. {
  265.   fflush (fp);
  266.   if (fp != stdin && fp != stdout)
  267.     {
  268.       if (fclose (fp) != 0)
  269.     {
  270.       error (0, errno, "error closing file");
  271.       cleanup ();
  272.       exit (2);
  273.     }
  274.     }
  275.   else
  276.     /* Allow reading stdin from tty more than once. */
  277.     clearerr (fp);
  278. }
  279.  
  280. static void
  281. xfwrite (buf, size, nelem, fp)
  282.      char *buf;
  283.      int size, nelem;
  284.      FILE *fp;
  285. {
  286.   if (fwrite (buf, size, nelem, fp) != (unsigned) nelem)
  287.     {
  288.       error (0, errno, "write error");
  289.       cleanup ();
  290.       exit (2);
  291.     }
  292. }
  293.  
  294. /* Return a name for a temporary file. */
  295.  
  296. static char *
  297. tempname ()
  298. {
  299.   static int seq;
  300.   int len = strlen (temp_file_prefix);
  301.   char *name = xmalloc (len + 16);
  302.   struct tempnode *node =
  303.   (struct tempnode *) xmalloc (sizeof (struct tempnode));
  304.  
  305.   if (len && temp_file_prefix[len - 1] != '/')
  306.     sprintf (name, "%s/sort%5.5d%5.5d", temp_file_prefix, getpid (), ++seq);
  307.   else
  308.     sprintf (name, "%ssort%5.5d%5.5d", temp_file_prefix, getpid (), ++seq);
  309.   node->name = name;
  310.   node->next = temphead.next;
  311.   temphead.next = node;
  312.   return name;
  313. }
  314.  
  315. /* Search through the list of temporary files for NAME;
  316.    remove it if it is found on the list. */
  317.  
  318. static void
  319. zaptemp (name)
  320.      char *name;
  321. {
  322.   struct tempnode *node, *temp;
  323.  
  324.   for (node = &temphead; node->next; node = node->next)
  325.     if (!strcmp (name, node->next->name))
  326.       break;
  327.   if (node->next)
  328.     {
  329.       temp = node->next;
  330.       unlink (temp->name);
  331.       free (temp->name);
  332.       node->next = temp->next;
  333.       free ((char *) temp);
  334.     }
  335. }
  336.  
  337. /* Initialize the character class tables. */
  338.  
  339. static void
  340. inittables ()
  341. {
  342.   int i;
  343.  
  344.   for (i = 0; i < UCHAR_LIM; ++i)
  345.     {
  346.       if (ISBLANK (i))
  347.     blanks[i] = 1;
  348.       if (ISDIGIT (i))
  349.     digits[i] = 1;
  350.       if (!ISPRINT (i))
  351.     nonprinting[i] = 1;
  352.       if (!ISALNUM (i) && !ISBLANK (i))
  353.     nondictionary[i] = 1;
  354.       if (ISLOWER (i))
  355.     fold_toupper[i] = toupper (i);
  356.       else
  357.     fold_toupper[i] = i;
  358.     }
  359. }
  360.  
  361. /* Initialize BUF, allocating ALLOC bytes initially. */
  362.  
  363. static void
  364. initbuf (buf, alloc)
  365.      struct buffer *buf;
  366.      int alloc;
  367. {
  368.   buf->alloc = alloc;
  369.   buf->buf = xmalloc (buf->alloc);
  370.   buf->used = buf->left = 0;
  371. }
  372.  
  373. /* Fill BUF reading from FP, moving buf->left bytes from the end
  374.    of buf->buf to the beginning first.    If EOF is reached and the
  375.    file wasn't terminated by a newline, supply one.  Return a count
  376.    of bytes buffered. */
  377.  
  378. static int
  379. fillbuf (buf, fp)
  380.      struct buffer *buf;
  381.      FILE *fp;
  382. {
  383.   int cc;
  384.  
  385.   bcopy (buf->buf + buf->used - buf->left, buf->buf, buf->left);
  386.   buf->used = buf->left;
  387.  
  388.   while (!feof (fp) && (buf->used == 0 || !memchr (buf->buf, '\n', buf->used)))
  389.     {
  390.       if (buf->used == buf->alloc)
  391.     {
  392.       buf->alloc *= 2;
  393.       buf->buf = xrealloc (buf->buf, buf->alloc);
  394.     }
  395.       cc = fread (buf->buf + buf->used, 1, buf->alloc - buf->used, fp);
  396.       if (ferror (fp))
  397.     {
  398.       error (0, errno, "read error");
  399.       cleanup ();
  400.       exit (2);
  401.     }
  402.       buf->used += cc;
  403.     }
  404.  
  405.   if (feof (fp) && buf->used && buf->buf[buf->used - 1] != '\n')
  406.     {
  407.       if (buf->used == buf->alloc)
  408.     {
  409.       buf->alloc *= 2;
  410.       buf->buf = xrealloc (buf->buf, buf->alloc);
  411.     }
  412.       buf->buf[buf->used++] = '\n';
  413.     }
  414.  
  415.   return buf->used;
  416. }
  417.  
  418. /* Initialize LINES, allocating space for ALLOC lines initially.
  419.    LIMIT is the maximum possible number of lines to allocate space
  420.    for, ever.  */
  421.  
  422. static void
  423. initlines (lines, alloc, limit)
  424.      struct lines *lines;
  425.      int alloc;
  426.      int limit;
  427. {
  428.   lines->alloc = alloc;
  429.   lines->lines = (struct line *) xmalloc (lines->alloc * sizeof (struct line));
  430.   lines->used = 0;
  431.   lines->limit = limit;
  432. }
  433.  
  434. /* Return a pointer to the first character of the field specified
  435.    by KEY in LINE. */
  436.  
  437. static char *
  438. begfield (line, key)
  439.      struct line *line;
  440.      struct keyfield *key;
  441. {
  442.   register char *ptr = line->text, *lim = ptr + line->length;
  443.   register int sword = key->sword, schar = key->schar;
  444.  
  445.   if (tab)
  446.     while (ptr < lim && sword--)
  447.       {
  448.     while (ptr < lim && *ptr != tab)
  449.       ++ptr;
  450.     if (ptr < lim)
  451.       ++ptr;
  452.       }
  453.   else
  454.     while (ptr < lim && sword--)
  455.       {
  456.     while (ptr < lim && blanks[UCHAR (*ptr)])
  457.       ++ptr;
  458.     while (ptr < lim && !blanks[UCHAR (*ptr)])
  459.       ++ptr;
  460.       }
  461.  
  462.   if (key->skipsblanks)
  463.     while (ptr < lim && blanks[UCHAR (*ptr)])
  464.       ++ptr;
  465.  
  466.   while (ptr < lim && schar--)
  467.     ++ptr;
  468.  
  469.   return ptr;
  470. }
  471.  
  472. /* Return the limit of (a pointer to the first character after) the field
  473.    in LINE specified by KEY. */
  474.  
  475. static char *
  476. limfield (line, key)
  477.      struct line *line;
  478.      struct keyfield *key;
  479. {
  480.   register char *ptr = line->text, *lim = ptr + line->length;
  481.   register int eword = key->eword, echar = key->echar;
  482.  
  483.   if (tab)
  484.     while (ptr < lim && eword--)
  485.       {
  486.     while (ptr < lim && *ptr != tab)
  487.       ++ptr;
  488.     if (ptr < lim && (eword || key->skipeblanks))
  489.       ++ptr;
  490.       }
  491.   else
  492.     while (ptr < lim && eword--)
  493.       {
  494.     while (ptr < lim && blanks[UCHAR (*ptr)])
  495.       ++ptr;
  496.     while (ptr < lim && !blanks[UCHAR (*ptr)])
  497.       ++ptr;
  498.       }
  499.  
  500.   if (key->skipeblanks)
  501.     while (ptr < lim && blanks[UCHAR (*ptr)])
  502.       ++ptr;
  503.  
  504.   while (ptr < lim && echar--)
  505.     ++ptr;
  506.  
  507.   return ptr;
  508. }
  509.  
  510. /* Find the lines in BUF, storing pointers and lengths in LINES.
  511.    Also replace newlines with NULs. */
  512.  
  513. static void
  514. findlines (buf, lines)
  515.      struct buffer *buf;
  516.      struct lines *lines;
  517. {
  518.   register char *beg = buf->buf, *lim = buf->buf + buf->used, *ptr;
  519.   struct keyfield *key = keyhead.next;
  520.  
  521.   lines->used = 0;
  522.  
  523.   while (beg < lim && (ptr = memchr (beg, '\n', lim - beg))
  524.      && lines->used < lines->limit)
  525.     {
  526.       /* There are various places in the code that rely on a NUL
  527.      being at the end of in-core lines; NULs inside the lines
  528.      will not cause trouble, though. */
  529.       *ptr = '\0';
  530.  
  531.       if (lines->used == lines->alloc)
  532.     {
  533.       lines->alloc *= 2;
  534.       lines->lines = (struct line *)
  535.         xrealloc ((char *) lines->lines,
  536.               lines->alloc * sizeof (struct line));
  537.     }
  538.  
  539.       lines->lines[lines->used].text = beg;
  540.       lines->lines[lines->used].length = ptr - beg;
  541.  
  542.       /* Precompute the position of the first key for efficiency. */
  543.       if (key)
  544.     {
  545.       if (key->eword >= 0)
  546.         lines->lines[lines->used].keylim =
  547.           limfield (&lines->lines[lines->used], key);
  548.       else
  549.         lines->lines[lines->used].keylim = ptr;
  550.  
  551.       if (key->sword >= 0)
  552.         lines->lines[lines->used].keybeg =
  553.           begfield (&lines->lines[lines->used], key);
  554.       else
  555.         {
  556.           if (key->skipsblanks)
  557.         while (blanks[UCHAR (*beg)])
  558.           ++beg;
  559.           lines->lines[lines->used].keybeg = beg;
  560.         }
  561.     }
  562.       else
  563.     {
  564.       lines->lines[lines->used].keybeg = 0;
  565.       lines->lines[lines->used].keylim = 0;
  566.     }
  567.  
  568.       ++lines->used;
  569.       beg = ptr + 1;
  570.     }
  571.  
  572.   buf->left = lim - beg;
  573. }
  574.  
  575. /* Compare strings A and B containing decimal fractions < 1.  Each string
  576.    should begin with a decimal point followed immediately by the digits
  577.    of the fraction.  Strings not of this form are considered to be zero. */
  578.  
  579. static int
  580. fraccompare (a, b)
  581.      register char *a, *b;
  582. {
  583.   register tmpa = UCHAR (*a), tmpb = UCHAR (*b);
  584.  
  585.   if (tmpa == '.' && tmpb == '.')
  586.     {
  587.       do
  588.     tmpa = UCHAR (*++a), tmpb = UCHAR (*++b);
  589.       while (tmpa == tmpb && digits[tmpa]);
  590.       if (digits[tmpa] && digits[tmpb])
  591.     return tmpa - tmpb;
  592.       if (digits[tmpa])
  593.     {
  594.       while (tmpa == '0')
  595.         tmpa = UCHAR (*++a);
  596.       if (digits[tmpa])
  597.         return 1;
  598.       return 0;
  599.     }
  600.       if (digits[tmpb])
  601.     {
  602.       while (tmpb == '0')
  603.         tmpb = UCHAR (*++b);
  604.       if (digits[tmpb])
  605.         return -1;
  606.       return 0;
  607.     }
  608.       return 0;
  609.     }
  610.   else if (tmpa == '.')
  611.     {
  612.       do
  613.     tmpa = UCHAR (*++a);
  614.       while (tmpa == '0');
  615.       if (digits[tmpa])
  616.     return 1;
  617.       return 0;
  618.     }
  619.   else if (tmpb == '.')
  620.     {
  621.       do
  622.     tmpb = UCHAR (*++b);
  623.       while (tmpb == '0');
  624.       if (digits[tmpb])
  625.     return -1;
  626.       return 0;
  627.     }
  628.   return 0;
  629. }
  630.  
  631. /* Compare strings A and B as numbers without explicitly converting them to
  632.    machine numbers.  Comparatively slow for short strings, but asymptotically
  633.    hideously fast. */
  634.  
  635. static int
  636. numcompare (a, b)
  637.      register char *a, *b;
  638. {
  639.   register int tmpa, tmpb, loga, logb, tmp;
  640.  
  641.   tmpa = UCHAR (*a), tmpb = UCHAR (*b);
  642.  
  643.   while (blanks[tmpa])
  644.     tmpa = UCHAR (*++a);
  645.   while (blanks[tmpb])
  646.     tmpb = UCHAR (*++b);
  647.  
  648.   if (tmpa == '-')
  649.     {
  650.       tmpa = UCHAR (*++a);
  651.       if (tmpb != '-')
  652.     {
  653.       if (digits[tmpa] && digits[tmpb])
  654.         return -1;
  655.       return 0;
  656.     }
  657.       tmpb = UCHAR (*++b);
  658.  
  659.       while (tmpa == '0')
  660.     tmpa = UCHAR (*++a);
  661.       while (tmpb == '0')
  662.     tmpb = UCHAR (*++b);
  663.  
  664.       while (tmpa == tmpb && digits[tmpa])
  665.     tmpa = UCHAR (*++a), tmpb = UCHAR (*++b);
  666.  
  667.       if ((tmpa == '.' && !digits[tmpb]) || (tmpb == '.' && !digits[tmpa]))
  668.     return -fraccompare (a, b);
  669.  
  670.       if (digits[tmpa])
  671.     for (loga = 1; digits[UCHAR (*++a)]; ++loga)
  672.       ;
  673.       else
  674.     loga = 0;
  675.  
  676.       if (digits[tmpb])
  677.     for (logb = 1; digits[UCHAR (*++b)]; ++logb)
  678.       ;
  679.       else
  680.     logb = 0;
  681.  
  682.       if ((tmp = logb - loga) != 0)
  683.     return tmp;
  684.  
  685.       if (!loga)
  686.     return 0;
  687.  
  688.       return tmpb - tmpa;
  689.     }
  690.   else if (tmpb == '-')
  691.     {
  692.       if (digits[UCHAR (tmpa)] && digits[UCHAR (*++b)])
  693.     return 1;
  694.       return 0;
  695.     }
  696.   else
  697.     {
  698.       while (tmpa == '0')
  699.     tmpa = UCHAR (*++a);
  700.       while (tmpb == '0')
  701.     tmpb = UCHAR (*++b);
  702.  
  703.       while (tmpa == tmpb && digits[tmpa])
  704.     tmpa = UCHAR (*++a), tmpb = UCHAR (*++b);
  705.  
  706.       if ((tmpa == '.' && !digits[tmpb]) || (tmpb == '.' && !digits[tmpa]))
  707.     return fraccompare (a, b);
  708.  
  709.       if (digits[tmpa])
  710.     for (loga = 1; digits[UCHAR (*++a)]; ++loga)
  711.       ;
  712.       else
  713.     loga = 0;
  714.  
  715.       if (digits[tmpb])
  716.     for (logb = 1; digits[UCHAR (*++b)]; ++logb)
  717.       ;
  718.       else
  719.     logb = 0;
  720.  
  721.       if ((tmp = loga - logb) != 0)
  722.     return tmp;
  723.  
  724.       if (!loga)
  725.     return 0;
  726.  
  727.       return tmpa - tmpb;
  728.     }
  729. }
  730.  
  731. /* Return an integer <= 12 associated with month name S with length LEN,
  732.    0 if the name in S is not recognized. */
  733.  
  734. static int
  735. getmonth (s, len)
  736.      char *s;
  737.      int len;
  738. {
  739.   char month[4];
  740.   register int i, lo = 0, hi = 12;
  741.  
  742.   while (len > 0 && blanks[UCHAR(*s)])
  743.     ++s, --len;
  744.  
  745.   if (len < 3)
  746.     return 0;
  747.  
  748.   for (i = 0; i < 3; ++i)
  749.     month[i] = fold_toupper[UCHAR (s[i])];
  750.   month[3] = '\0';
  751.  
  752.   while (hi - lo > 1)
  753.     if (strcmp (month, monthtab[(lo + hi) / 2].name) < 0)
  754.       hi = (lo + hi) / 2;
  755.     else
  756.       lo = (lo + hi) / 2;
  757.   if (!strcmp (month, monthtab[lo].name))
  758.     return monthtab[lo].val;
  759.   return 0;
  760. }
  761.  
  762. /* Compare two lines A and B trying every key in sequence until there
  763.    are no more keys or a difference is found. */
  764.  
  765. static int
  766. keycompare (a, b)
  767.      struct line *a, *b;
  768. {
  769.   register char *texta, *textb, *lima, *limb, *translate;
  770.   register int *ignore;
  771.   struct keyfield *key;
  772.   int diff = 0, iter = 0, lena, lenb;
  773.  
  774.   for (key = keyhead.next; key; key = key->next, ++iter)
  775.     {
  776.       ignore = key->ignore;
  777.       translate = key->translate;
  778.  
  779.       /* Find the beginning and limit of each field. */
  780.       if (iter || a->keybeg == NULL || b->keybeg == NULL)
  781.     {
  782.       if (key->eword >= 0)
  783.         lima = limfield (a, key), limb = limfield (b, key);
  784.       else
  785.         lima = a->text + a->length, limb = b->text + b->length;
  786.  
  787.       if (key->sword >= 0)
  788.         texta = begfield (a, key), textb = begfield (b, key);
  789.       else
  790.         {
  791.           texta = a->text, textb = b->text;
  792.           if (key->skipsblanks)
  793.         {
  794.           while (texta < lima && blanks[UCHAR (*texta)])
  795.             ++texta;
  796.           while (textb < limb && blanks[UCHAR (*textb)])
  797.             ++textb;
  798.         }
  799.         }
  800.     }
  801.       else
  802.     {
  803.       /* For the first iteration only, the key positions have
  804.          been precomputed for us. */
  805.       texta = a->keybeg, lima = a->keylim;
  806.       textb = b->keybeg, limb = b->keylim;
  807.     }
  808.  
  809.       /* Find the lengths. */
  810.       lena = lima - texta, lenb = limb - textb;
  811.       if (lena < 0)
  812.     lena = 0;
  813.       if (lenb < 0)
  814.     lenb = 0;
  815.  
  816.       /* Actually compare the fields. */
  817.       if (key->numeric)
  818.     {
  819.       if (*lima || *limb)
  820.         {
  821.           char savea = *lima, saveb = *limb;
  822.  
  823.           *lima = *limb = '\0';
  824.           diff = numcompare (texta, textb);
  825.           *lima = savea, *limb = saveb;
  826.         }
  827.       else
  828.         diff = numcompare (texta, textb);
  829.  
  830.       if (diff)
  831.         return key->reverse ? -diff : diff;
  832.       continue;
  833.     }
  834.       else if (key->month)
  835.     {
  836.       diff = getmonth (texta, lena) - getmonth (textb, lenb);
  837.       if (diff)
  838.         return key->reverse ? -diff : diff;
  839.       continue;
  840.     }
  841.       else if (ignore && translate)
  842.     while (texta < lima && textb < limb)
  843.       {
  844.         while (texta < lima && ignore[UCHAR (*texta)])
  845.           ++texta;
  846.         while (textb < limb && ignore[UCHAR (*textb)])
  847.           ++textb;
  848.         if (texta < lima && textb < limb &&
  849.         translate[UCHAR (*texta++)] != translate[UCHAR (*textb++)])
  850.           {
  851.         diff = translate[UCHAR (*--texta)] - translate[UCHAR (*--textb)];
  852.         break;
  853.           }
  854.       }
  855.       else if (ignore)
  856.     while (texta < lima && textb < limb)
  857.       {
  858.         while (texta < lima && ignore[UCHAR (*texta)])
  859.           ++texta;
  860.         while (textb < limb && ignore[UCHAR (*textb)])
  861.           ++textb;
  862.         if (texta < lima && textb < limb && *texta++ != *textb++)
  863.           {
  864.         diff = *--texta - *--textb;
  865.         break;
  866.           }
  867.       }
  868.       else if (translate)
  869.     while (texta < lima && textb < limb)
  870.       {
  871.         if (translate[UCHAR (*texta++)] != translate[UCHAR (*textb++)])
  872.           {
  873.         diff = translate[UCHAR (*--texta)] - translate[UCHAR (*--textb)];
  874.         break;
  875.           }
  876.       }
  877.       else
  878.     diff = memcmp (texta, textb, min (lena, lenb));
  879.  
  880.       if (diff)
  881.     return key->reverse ? -diff : diff;
  882.       if ((diff = lena - lenb) != 0)
  883.     return key->reverse ? -diff : diff;
  884.     }
  885.  
  886.   return 0;
  887. }
  888.  
  889. /* Compare two lines A and B, returning negative, zero, or positive
  890.    depending on whether A compares less than, equal to, or greater than B. */
  891.  
  892. static int
  893. compare (a, b)
  894.      register struct line *a, *b;
  895. {
  896.   int diff, tmpa, tmpb, mini;
  897.  
  898.   /* First try to compare on the specified keys (if any).
  899.      The only two cases with no key at all are unadorned sort,
  900.      and unadorned sort -r. */
  901.   if (keyhead.next)
  902.     {
  903.       diff = keycompare (a, b);
  904.       if (diff != 0)
  905.     return diff;
  906.       if (unique || stable)
  907.     return 0;
  908.     }
  909.  
  910.   /* If the keys all compare equal (or no keys were specified)
  911.      fall through to the default byte-by-byte comparison. */
  912.   tmpa = a->length, tmpb = b->length;
  913.   mini = min (tmpa, tmpb);
  914.   if (mini == 0)
  915.     diff = tmpa - tmpb;
  916.   else
  917.     {
  918.       char *ap = a->text, *bp = b->text;
  919.  
  920.       diff = UCHAR (*ap) - UCHAR (*bp);
  921.       if (diff == 0)
  922.     {
  923.       diff = memcmp (ap, bp, mini);
  924.       if (diff == 0)
  925.         diff = tmpa - tmpb;
  926.     }
  927.     }
  928.  
  929.   return reverse ? -diff : diff;
  930. }
  931.  
  932. /* Check that the lines read from the given FP come in order.  Return
  933.    1 if they do and 0 if there is a disorder. */
  934.  
  935. static int
  936. checkfp (fp)
  937.      FILE *fp;
  938. {
  939.   struct buffer buf;        /* Input buffer. */
  940.   struct lines lines;        /* Lines scanned from the buffer. */
  941.   struct line temp;        /* Copy of previous line. */
  942.   int cc;            /* Character count. */
  943.   int cmp;            /* Result of calling compare. */
  944.   int alloc, i, success = 1;
  945.  
  946.   initbuf (&buf, mergealloc);
  947.   initlines (&lines, mergealloc / linelength + 1,
  948.          LINEALLOC / ((NMERGE + NMERGE) * sizeof (struct line)));
  949.   alloc = linelength;
  950.   temp.text = xmalloc (alloc);
  951.  
  952.   cc = fillbuf (&buf, fp);
  953.   findlines (&buf, &lines);
  954.  
  955.   if (cc)
  956.     do
  957.       {
  958.     /* Compare each line in the buffer with its successor. */
  959.     for (i = 0; i < lines.used - 1; ++i)
  960.       {
  961.         cmp = compare (&lines.lines[i], &lines.lines[i + 1]);
  962.         if ((unique && cmp >= 0) || (cmp > 0))
  963.           {
  964.         success = 0;
  965.         goto finish;
  966.           }
  967.       }
  968.  
  969.     /* Save the last line of the buffer and refill the buffer. */
  970.     if (lines.lines[lines.used - 1].length > alloc)
  971.       {
  972.         while (lines.lines[lines.used - 1].length + 1 > alloc)
  973.           alloc *= 2;
  974.         temp.text = xrealloc (temp.text, alloc);
  975.       }
  976.     bcopy (lines.lines[lines.used - 1].text, temp.text,
  977.            lines.lines[lines.used - 1].length + 1);
  978.     temp.length = lines.lines[lines.used - 1].length;
  979.  
  980.     cc = fillbuf (&buf, fp);
  981.     if (cc)
  982.       {
  983.         findlines (&buf, &lines);
  984.         /* Make sure the line saved from the old buffer contents is
  985.            less than or equal to the first line of the new buffer. */
  986.         cmp = compare (&temp, &lines.lines[0]);
  987.         if ((unique && cmp >= 0) || (cmp > 0))
  988.           {
  989.         success = 0;
  990.         break;
  991.           }
  992.       }
  993.       }
  994.     while (cc);
  995.  
  996. finish:
  997.   xfclose (fp);
  998.   free (buf.buf);
  999.   free ((char *) lines.lines);
  1000.   free (temp.text);
  1001.   return success;
  1002. }
  1003.  
  1004. /* Merge lines from FPS onto OFP.  NFPS cannot be greater than NMERGE.
  1005.    Close FPS before returning. */
  1006.  
  1007. static void
  1008. mergefps (fps, nfps, ofp)
  1009.      FILE *fps[], *ofp;
  1010.      register int nfps;
  1011. {
  1012.   struct buffer buffer[NMERGE];    /* Input buffers for each file. */
  1013.   struct lines lines[NMERGE];    /* Line tables for each buffer. */
  1014.   struct line saved;        /* Saved line for unique check. */
  1015.   int savedflag = 0;        /* True if there is a saved line. */
  1016.   int savealloc;        /* Size allocated for the saved line. */
  1017.   int cur[NMERGE];        /* Current line in each line table. */
  1018.   int ord[NMERGE];        /* Table representing a permutation of fps,
  1019.                    such that lines[ord[0]].lines[cur[ord[0]]]
  1020.                    is the smallest line and will be next
  1021.                    output. */
  1022.   register int i, j, t;
  1023.  
  1024.   /* Allocate space for a saved line if necessary. */
  1025.   if (unique)
  1026.     {
  1027.       savealloc = linelength;
  1028.       saved.text = xmalloc (savealloc);
  1029.     }
  1030.  
  1031.   /* Read initial lines from each input file. */
  1032.   for (i = 0; i < nfps; ++i)
  1033.     {
  1034.       initbuf (&buffer[i], mergealloc);
  1035.       /* If a file is empty, eliminate it from future consideration. */
  1036.       while (i < nfps && !fillbuf (&buffer[i], fps[i]))
  1037.     {
  1038.       xfclose (fps[i]);
  1039.       --nfps;
  1040.       for (j = i; j < nfps; ++j)
  1041.         fps[j] = fps[j + 1];
  1042.     }
  1043.       if (i == nfps)
  1044.     free (buffer[i].buf);
  1045.       else
  1046.     {
  1047.       initlines (&lines[i], mergealloc / linelength + 1,
  1048.              LINEALLOC / ((NMERGE + NMERGE) * sizeof (struct line)));
  1049.       findlines (&buffer[i], &lines[i]);
  1050.       cur[i] = 0;
  1051.     }
  1052.     }
  1053.  
  1054.   /* Set up the ord table according to comparisons among input lines.
  1055.      Since this only reorders two items if one is strictly greater than
  1056.      the other, it is stable. */
  1057.   for (i = 0; i < nfps; ++i)
  1058.     ord[i] = i;
  1059.   for (i = 1; i < nfps; ++i)
  1060.     if (compare (&lines[ord[i - 1]].lines[cur[ord[i - 1]]],
  1061.          &lines[ord[i]].lines[cur[ord[i]]]) > 0)
  1062.       t = ord[i - 1], ord[i - 1] = ord[i], ord[i] = t, i = 0;
  1063.  
  1064.   /* Repeatedly output the smallest line until no input remains. */
  1065.   while (nfps)
  1066.     {
  1067.       /* If uniqified output is turned out, output only the first of
  1068.      an identical series of lines. */
  1069.       if (unique)
  1070.     {
  1071.       if (savedflag && compare (&saved, &lines[ord[0]].lines[cur[ord[0]]]))
  1072.         {
  1073.           xfwrite (saved.text, 1, saved.length, ofp);
  1074.           putc ('\n', ofp);
  1075.           savedflag = 0;
  1076.         }
  1077.       if (!savedflag)
  1078.         {
  1079.           if (savealloc < lines[ord[0]].lines[cur[ord[0]]].length + 1)
  1080.         {
  1081.           while (savealloc < lines[ord[0]].lines[cur[ord[0]]].length + 1)
  1082.             savealloc *= 2;
  1083.           saved.text = xrealloc (saved.text, savealloc);
  1084.         }
  1085.           saved.length = lines[ord[0]].lines[cur[ord[0]]].length;
  1086.           bcopy (lines[ord[0]].lines[cur[ord[0]]].text, saved.text,
  1087.              saved.length + 1);
  1088.           if (lines[ord[0]].lines[cur[ord[0]]].keybeg != NULL)
  1089.         {
  1090.           saved.keybeg = saved.text +
  1091.             (lines[ord[0]].lines[cur[ord[0]]].keybeg
  1092.              - lines[ord[0]].lines[cur[ord[0]]].text);
  1093.         }
  1094.           if (lines[ord[0]].lines[cur[ord[0]]].keylim != NULL)
  1095.         {
  1096.           saved.keylim = saved.text +
  1097.             (lines[ord[0]].lines[cur[ord[0]]].keylim
  1098.              - lines[ord[0]].lines[cur[ord[0]]].text);
  1099.         }
  1100.           savedflag = 1;
  1101.         }
  1102.     }
  1103.       else
  1104.     {
  1105.       xfwrite (lines[ord[0]].lines[cur[ord[0]]].text, 1,
  1106.            lines[ord[0]].lines[cur[ord[0]]].length, ofp);
  1107.       putc ('\n', ofp);
  1108.     }
  1109.  
  1110.       /* Check if we need to read more lines into core. */
  1111.       if (++cur[ord[0]] == lines[ord[0]].used)
  1112.     if (fillbuf (&buffer[ord[0]], fps[ord[0]]))
  1113.       {
  1114.         findlines (&buffer[ord[0]], &lines[ord[0]]);
  1115.         cur[ord[0]] = 0;
  1116.       }
  1117.     else
  1118.       {
  1119.         /* We reached EOF on fps[ord[0]]. */
  1120.         for (i = 1; i < nfps; ++i)
  1121.           if (ord[i] > ord[0])
  1122.         --ord[i];
  1123.         --nfps;
  1124.         xfclose (fps[ord[0]]);
  1125.         free (buffer[ord[0]].buf);
  1126.         free ((char *) lines[ord[0]].lines);
  1127.         for (i = ord[0]; i < nfps; ++i)
  1128.           {
  1129.         fps[i] = fps[i + 1];
  1130.         buffer[i] = buffer[i + 1];
  1131.         lines[i] = lines[i + 1];
  1132.         cur[i] = cur[i + 1];
  1133.           }
  1134.         for (i = 0; i < nfps; ++i)
  1135.           ord[i] = ord[i + 1];
  1136.         continue;
  1137.       }
  1138.  
  1139.       /* The new line just read in may be larger than other lines
  1140.      already in core; push it back in the queue until we encounter
  1141.      a line larger than it. */
  1142.       for (i = 1; i < nfps; ++i)
  1143.     {
  1144.       t = compare (&lines[ord[0]].lines[cur[ord[0]]],
  1145.                &lines[ord[i]].lines[cur[ord[i]]]);
  1146.       if (!t)
  1147.         t = ord[0] - ord[i];
  1148.       if (t < 0)
  1149.         break;
  1150.     }
  1151.       t = ord[0];
  1152.       for (j = 1; j < i; ++j)
  1153.     ord[j - 1] = ord[j];
  1154.       ord[i - 1] = t;
  1155.     }
  1156.  
  1157.   if (unique && savedflag)
  1158.     {
  1159.       xfwrite (saved.text, 1, saved.length, ofp);
  1160.       putc ('\n', ofp);
  1161.       free (saved.text);
  1162.     }
  1163. }
  1164.  
  1165. /* Sort the array LINES with NLINES members, using TEMP for temporary space. */
  1166.  
  1167. static void
  1168. sortlines (lines, nlines, temp)
  1169.      struct line *lines, *temp;
  1170.      int nlines;
  1171. {
  1172.   register struct line *lo, *hi, *t;
  1173.   register int nlo, nhi;
  1174.  
  1175.   if (nlines == 2)
  1176.     {
  1177.       if (compare (&lines[0], &lines[1]) > 0)
  1178.     *temp = lines[0], lines[0] = lines[1], lines[1] = *temp;
  1179.       return;
  1180.     }
  1181.  
  1182.   nlo = nlines / 2;
  1183.   lo = lines;
  1184.   nhi = nlines - nlo;
  1185.   hi = lines + nlo;
  1186.  
  1187.   if (nlo > 1)
  1188.     sortlines (lo, nlo, temp);
  1189.  
  1190.   if (nhi > 1)
  1191.     sortlines (hi, nhi, temp);
  1192.  
  1193.   t = temp;
  1194.  
  1195.   while (nlo && nhi)
  1196.     if (compare (lo, hi) <= 0)
  1197.       *t++ = *lo++, --nlo;
  1198.     else
  1199.       *t++ = *hi++, --nhi;
  1200.   while (nlo--)
  1201.     *t++ = *lo++;
  1202.  
  1203.   for (lo = lines, nlo = nlines - nhi, t = temp; nlo; --nlo)
  1204.     *lo++ = *t++;
  1205. }
  1206.  
  1207. /* Check that each of the NFILES FILES is ordered.
  1208.    Return a count of disordered files. */
  1209.  
  1210. static int
  1211. check (files, nfiles)
  1212.      char *files[];
  1213.      int nfiles;
  1214. {
  1215.   int i, disorders = 0;
  1216.   FILE *fp;
  1217.  
  1218.   for (i = 0; i < nfiles; ++i)
  1219.     {
  1220.       fp = xfopen (files[i], "r");
  1221.       if (!checkfp (fp))
  1222.     {
  1223.       printf ("%s: disorder on %s\n", program_name, files[i]);
  1224.       ++disorders;
  1225.     }
  1226.     }
  1227.   return disorders;
  1228. }
  1229.  
  1230. /* Merge NFILES FILES onto OFP. */
  1231.  
  1232. static void
  1233. merge (files, nfiles, ofp)
  1234.      char *files[];
  1235.      int nfiles;
  1236.      FILE *ofp;
  1237. {
  1238.   int i, j, t;
  1239.   char *temp;
  1240.   FILE *fps[NMERGE], *tfp;
  1241.  
  1242.   while (nfiles > NMERGE)
  1243.     {
  1244.       t = 0;
  1245.       for (i = 0; i < nfiles / NMERGE; ++i)
  1246.     {
  1247.       for (j = 0; j < NMERGE; ++j)
  1248.         fps[j] = xfopen (files[i * NMERGE + j], "r");
  1249.       tfp = xfopen (temp = tempname (), "w");
  1250.       mergefps (fps, NMERGE, tfp);
  1251.       xfclose (tfp);
  1252.       for (j = 0; j < NMERGE; ++j)
  1253.         zaptemp (files[i * NMERGE + j]);
  1254.       files[t++] = temp;
  1255.     }
  1256.       for (j = 0; j < nfiles % NMERGE; ++j)
  1257.     fps[j] = xfopen (files[i * NMERGE + j], "r");
  1258.       tfp = xfopen (temp = tempname (), "w");
  1259.       mergefps (fps, nfiles % NMERGE, tfp);
  1260.       xfclose (tfp);
  1261.       for (j = 0; j < nfiles % NMERGE; ++j)
  1262.     zaptemp (files[i * NMERGE + j]);
  1263.       files[t++] = temp;
  1264.       nfiles = t;
  1265.     }
  1266.  
  1267.   for (i = 0; i < nfiles; ++i)
  1268.     fps[i] = xfopen (files[i], "r");
  1269.   mergefps (fps, i, ofp);
  1270.   for (i = 0; i < nfiles; ++i)
  1271.     zaptemp (files[i]);
  1272. }
  1273.  
  1274. /* Sort NFILES FILES onto OFP. */
  1275.  
  1276. static void
  1277. sort (files, nfiles, ofp)
  1278.      char **files;
  1279.      int nfiles;
  1280.      FILE *ofp;
  1281. {
  1282.   struct buffer buf;
  1283.   struct lines lines;
  1284.   struct line *tmp;
  1285.   int i, ntmp;
  1286.   FILE *fp, *tfp;
  1287.   struct tempnode *node;
  1288.   int ntemp = 0;
  1289.   char **tempfiles;
  1290.  
  1291.   initbuf (&buf, sortalloc);
  1292.   initlines (&lines, sortalloc / linelength + 1,
  1293.          LINEALLOC / sizeof (struct line));
  1294.   ntmp = lines.alloc;
  1295.   tmp = (struct line *) xmalloc (ntmp * sizeof (struct line));
  1296.  
  1297.   while (nfiles--)
  1298.     {
  1299.       fp = xfopen (*files++, "r");
  1300.       while (fillbuf (&buf, fp))
  1301.     {
  1302.       findlines (&buf, &lines);
  1303.       if (lines.used > ntmp)
  1304.         {
  1305.           while (lines.used > ntmp)
  1306.         ntmp *= 2;
  1307.           tmp = (struct line *)
  1308.         xrealloc ((char *) tmp, ntmp * sizeof (struct line));
  1309.         }
  1310.       sortlines (lines.lines, lines.used, tmp);
  1311.       if (feof (fp) && !nfiles && !ntemp && !buf.left)
  1312.         tfp = ofp;
  1313.       else
  1314.         {
  1315.           ++ntemp;
  1316.           tfp = xfopen (tempname (), "w");
  1317.         }
  1318.       for (i = 0; i < lines.used; ++i)
  1319.         if (!unique || i == 0
  1320.         || compare (&lines.lines[i], &lines.lines[i - 1]))
  1321.           {
  1322.         xfwrite (lines.lines[i].text, 1, lines.lines[i].length, tfp);
  1323.         putc ('\n', tfp);
  1324.           }
  1325.       if (tfp != ofp)
  1326.         xfclose (tfp);
  1327.     }
  1328.       xfclose (fp);
  1329.     }
  1330.  
  1331.   free (buf.buf);
  1332.   free ((char *) lines.lines);
  1333.   free ((char *) tmp);
  1334.  
  1335.   if (ntemp)
  1336.     {
  1337.       tempfiles = (char **) xmalloc (ntemp * sizeof (char *));
  1338.       i = ntemp;
  1339.       for (node = temphead.next; i > 0; node = node->next)
  1340.     tempfiles[--i] = node->name;
  1341.       merge (tempfiles, ntemp, ofp);
  1342.       free ((char *) tempfiles);
  1343.     }
  1344. }
  1345.  
  1346. /* Insert key KEY at the end of the list (`keyhead'). */
  1347.  
  1348. static void
  1349. insertkey (key)
  1350.      struct keyfield *key;
  1351. {
  1352.   struct keyfield *k = &keyhead;
  1353.  
  1354.   while (k->next)
  1355.     k = k->next;
  1356.   k->next = key;
  1357.   key->next = NULL;
  1358. }
  1359.  
  1360. static void
  1361. badfieldspec (s)
  1362.      char *s;
  1363. {
  1364.   error (2, 0, "invalid field specification `%s'", s);
  1365. }
  1366.  
  1367. /* Handle interrupts and hangups. */
  1368.  
  1369. static void
  1370. sighandler (sig)
  1371.      int sig;
  1372. {
  1373. #ifdef _POSIX_VERSION
  1374.   struct sigaction sigact;
  1375.  
  1376.   sigact.sa_handler = SIG_DFL;
  1377.   sigemptyset (&sigact.sa_mask);
  1378.   sigact.sa_flags = 0;
  1379.   sigaction (sig, &sigact, NULL);
  1380. #else                /* !_POSIX_VERSION */
  1381.   signal (sig, SIG_DFL);
  1382. #endif                /* _POSIX_VERSION */
  1383.   cleanup ();
  1384.   /* kill (getpid (), sig); */
  1385. }
  1386.  
  1387. /* Set the ordering options for KEY specified in S.
  1388.    Return the address of the first character in S that
  1389.    is not a valid ordering option.
  1390.    BLANKTYPE is the kind of blanks that 'b' should skip. */
  1391.  
  1392. static char *
  1393. set_ordering (s, key, blanktype)
  1394.      register char *s;
  1395.      struct keyfield *key;
  1396.      enum blanktype blanktype;
  1397. {
  1398.   while (*s)
  1399.     {
  1400.       switch (*s)
  1401.     {
  1402.     case 'b':
  1403.       if (blanktype == bl_start || blanktype == bl_both)
  1404.         key->skipsblanks = 1;
  1405.       if (blanktype == bl_end || blanktype == bl_both)
  1406.         key->skipeblanks = 1;
  1407.       break;
  1408.     case 'd':
  1409.       key->ignore = nondictionary;
  1410.       break;
  1411.     case 'f':
  1412.       key->translate = fold_toupper;
  1413.       break;
  1414. #if 0
  1415.     case 'g':
  1416.       /* Reserved for comparing floating-point numbers. */
  1417.       break;
  1418. #endif
  1419.     case 'i':
  1420.       key->ignore = nonprinting;
  1421.       break;
  1422.     case 'M':
  1423.       key->month = 1;
  1424.       break;
  1425.     case 'n':
  1426.       key->numeric = 1;
  1427.       break;
  1428.     case 'r':
  1429.       key->reverse = 1;
  1430.       break;
  1431.     default:
  1432.       return s;
  1433.     }
  1434.       ++s;
  1435.     }
  1436.   return s;
  1437. }
  1438.  
  1439. void
  1440. main (argc, argv)
  1441.      int argc;
  1442.      char *argv[];
  1443. {
  1444.   struct keyfield *key = NULL, gkey;
  1445.   char *s;
  1446.   int i, t, t2;
  1447.   int checkonly = 0, mergeonly = 0, nfiles = 0;
  1448.   char *minus = "-", *outfile = minus, **files, *tmp;
  1449.   FILE *ofp;
  1450. #ifdef _POSIX_VERSION
  1451.   struct sigaction oldact, newact;
  1452. #endif                /* _POSIX_VERSION */
  1453.  
  1454.   program_name = argv[0];
  1455.   have_read_stdin = 0;
  1456.   inittables ();
  1457.  
  1458.   temp_file_prefix = getenv ("TMPDIR");
  1459.   if (temp_file_prefix == NULL)
  1460.     temp_file_prefix = "/temp";
  1461.  
  1462. #ifdef _POSIX_VERSION
  1463.   newact.sa_handler = sighandler;
  1464.   sigemptyset (&newact.sa_mask);
  1465.   newact.sa_flags = 0;
  1466.  
  1467.   sigaction (SIGINT, NULL, &oldact);
  1468.   if (oldact.sa_handler != SIG_IGN)
  1469.     sigaction (SIGINT, &newact, NULL);
  1470.   sigaction (SIGHUP, NULL, &oldact);
  1471.   if (oldact.sa_handler != SIG_IGN)
  1472.     sigaction (SIGHUP, &newact, NULL);
  1473.   sigaction (SIGPIPE, NULL, &oldact);
  1474.   if (oldact.sa_handler != SIG_IGN)
  1475.     sigaction (SIGPIPE, &newact, NULL);
  1476.   sigaction (SIGTERM, NULL, &oldact);
  1477.   if (oldact.sa_handler != SIG_IGN)
  1478.     sigaction (SIGTERM, &newact, NULL);
  1479. #else                /* !_POSIX_VERSION */
  1480.   if (signal (SIGINT, SIG_IGN) != SIG_IGN)
  1481.     signal (SIGINT, (void *) sighandler);
  1482.   if (signal (SIGHUP, SIG_IGN) != SIG_IGN)
  1483.     signal (SIGHUP, (void *) sighandler);
  1484.   if (signal (SIGPIPE, SIG_IGN) != SIG_IGN)
  1485.     signal (SIGPIPE, (void *) sighandler);
  1486.   if (signal (SIGTERM, SIG_IGN) != SIG_IGN)
  1487.     signal (SIGTERM, (void *) sighandler);
  1488. #endif                /* !_POSIX_VERSION */
  1489.  
  1490.   gkey.sword = gkey.eword = -1;
  1491.   gkey.ignore = NULL;
  1492.   gkey.translate = NULL;
  1493.   gkey.numeric = gkey.month = gkey.reverse = 0;
  1494.   gkey.skipsblanks = gkey.skipeblanks = 0;
  1495.  
  1496.   files = (char **) xmalloc (sizeof (char *) * argc);
  1497.  
  1498.   for (i = 1; i < argc; ++i)
  1499.     {
  1500.       if (argv[i][0] == '+')
  1501.     {
  1502.       if (key)
  1503.         insertkey (key);
  1504.       key = (struct keyfield *) xmalloc (sizeof (struct keyfield));
  1505.       key->eword = -1;
  1506.       key->ignore = NULL;
  1507.       key->translate = NULL;
  1508.       key->skipsblanks = key->skipeblanks = 0;
  1509.       key->numeric = key->month = key->reverse = 0;
  1510.       s = argv[i] + 1;
  1511.       if (!digits[UCHAR (*s)])
  1512.         badfieldspec (argv[i]);
  1513.       for (t = 0; digits[UCHAR (*s)]; ++s)
  1514.         t = 10 * t + *s - '0';
  1515.       t2 = 0;
  1516.       if (*s == '.')
  1517.         for (++s; digits[UCHAR (*s)]; ++s)
  1518.           t2 = 10 * t2 + *s - '0';
  1519.       if (t2 || t)
  1520.         {
  1521.           key->sword = t;
  1522.           key->schar = t2;
  1523.         }
  1524.       else
  1525.         key->sword = -1;
  1526.       s = set_ordering (s, key, bl_start);
  1527.       if (*s)
  1528.         badfieldspec (argv[i]);
  1529.     }
  1530.       else if (argv[i][0] == '-' && argv[i][1])
  1531.     {
  1532.       s = argv[i] + 1;
  1533.       if (digits[UCHAR (*s)])
  1534.         {
  1535.           if (!key)
  1536.         usage ();
  1537.           for (t = 0; digits[UCHAR (*s)]; ++s)
  1538.         t = t * 10 + *s - '0';
  1539.           t2 = 0;
  1540.           if (*s == '.')
  1541.         for (++s; digits[UCHAR (*s)]; ++s)
  1542.           t2 = t2 * 10 + *s - '0';
  1543.           key->eword = t;
  1544.           key->echar = t2;
  1545.           s = set_ordering (s, key, bl_end);
  1546.           if (*s)
  1547.         badfieldspec (argv[i]);
  1548.           insertkey (key);
  1549.           key = NULL;
  1550.         }
  1551.       else
  1552.         while (*s)
  1553.           {
  1554.         s = set_ordering (s, &gkey, bl_both);
  1555.         switch (*s)
  1556.           {
  1557.           case '\0':
  1558.             break;
  1559.           case 'c':
  1560.             checkonly = 1;
  1561.             break;
  1562.           case 'k':
  1563.             if (s[1])
  1564.               ++s;
  1565.             else
  1566.               {
  1567.             if (i == argc - 1)
  1568.               error (2, 0, "option `-k' requires an argument");
  1569.             else
  1570.               s = argv[++i];
  1571.               }
  1572.             if (key)
  1573.               insertkey (key);
  1574.             key = (struct keyfield *)
  1575.               xmalloc (sizeof (struct keyfield));
  1576.             key->eword = -1;
  1577.             key->ignore = NULL;
  1578.             key->translate = NULL;
  1579.             key->skipsblanks = key->skipeblanks = 0;
  1580.             key->numeric = key->month = key->reverse = 0;
  1581.             /* Get POS1. */
  1582.             if (!digits[UCHAR (*s)])
  1583.               badfieldspec (argv[i]);
  1584.             for (t = 0; digits[UCHAR (*s)]; ++s)
  1585.               t = 10 * t + *s - '0';
  1586.             if (t)
  1587.               t--;
  1588.             t2 = 0;
  1589.             if (*s == '.')
  1590.               {
  1591.             for (++s; digits[UCHAR (*s)]; ++s)
  1592.               t2 = 10 * t2 + *s - '0';
  1593.             if (t2)
  1594.               t2--;
  1595.               }
  1596.             if (t2 || t)
  1597.               {
  1598.             key->sword = t;
  1599.             key->schar = t2;
  1600.               }
  1601.             else
  1602.               key->sword = -1;
  1603.             s = set_ordering (s, key, bl_start);
  1604.             if (*s && *s != ',')
  1605.               badfieldspec (argv[i]);
  1606.             else if (*s++)
  1607.               {
  1608.             /* Get POS2. */
  1609.             for (t = 0; digits[UCHAR (*s)]; ++s)
  1610.               t = t * 10 + *s - '0';
  1611.             t2 = 0;
  1612.             if (*s == '.')
  1613.               {
  1614.                 for (++s; digits[UCHAR (*s)]; ++s)
  1615.                   t2 = t2 * 10 + *s - '0';
  1616.                 if (t2)
  1617.                   t--;
  1618.               }
  1619.             key->eword = t;
  1620.             key->echar = t2;
  1621.             s = set_ordering (s, key, bl_end);
  1622.             if (*s)
  1623.               badfieldspec (argv[i]);
  1624.               }
  1625.             insertkey (key);
  1626.             key = NULL;
  1627.             goto outer;
  1628.           case 'm':
  1629.             mergeonly = 1;
  1630.             break;
  1631.           case 'o':
  1632.             if (s[1])
  1633.               outfile = s + 1;
  1634.             else
  1635.               {
  1636.             if (i == argc - 1)
  1637.               error (2, 0, "option `-o' requires an argument");
  1638.             else
  1639.               outfile = argv[++i];
  1640.               }
  1641.             goto outer;
  1642.           case 's':
  1643.             stable = 1;
  1644.             break;
  1645.           case 't':
  1646.             if (s[1])
  1647.               tab = *++s;
  1648.             else if (i < argc - 1)
  1649.               {
  1650.             tab = *argv[++i];
  1651.             goto outer;
  1652.               }
  1653.             else
  1654.               error (2, 0, "option `-t' requires an argument");
  1655.             break;
  1656.           case 'T':
  1657.             if (s[1])
  1658.               temp_file_prefix = ++s;
  1659.             else if (i < argc - 1)
  1660.               {
  1661.             temp_file_prefix = argv[++i];
  1662.             goto outer;
  1663.               }
  1664.             else
  1665.               error (2, 0, "option `-T' requires an argument");
  1666.             break;
  1667.           case 'u':
  1668.             unique = 1;
  1669.             break;
  1670.           default:
  1671.             fprintf (stderr, "%s: unrecognized option `-%c'\n",
  1672.                  argv[0], *s);
  1673.             usage ();
  1674.           }
  1675.         if (*s)
  1676.           ++s;
  1677.           }
  1678.     }
  1679.       else            /* Not an option. */
  1680.     {
  1681.       files[nfiles++] = argv[i];
  1682.     }
  1683.     outer:;
  1684.     }
  1685.  
  1686.   if (key)
  1687.     insertkey (key);
  1688.  
  1689.   /* Inheritance of global options to individual keys. */
  1690.   for (key = keyhead.next; key; key = key->next)
  1691.     if (!key->ignore && !key->translate && !key->skipsblanks && !key->reverse
  1692.     && !key->skipeblanks && !key->month && !key->numeric)
  1693.       {
  1694.     key->ignore = gkey.ignore;
  1695.     key->translate = gkey.translate;
  1696.     key->skipsblanks = gkey.skipsblanks;
  1697.     key->skipeblanks = gkey.skipeblanks;
  1698.     key->month = gkey.month;
  1699.     key->numeric = gkey.numeric;
  1700.     key->reverse = gkey.reverse;
  1701.       }
  1702.  
  1703.   if (!keyhead.next && (gkey.ignore || gkey.translate || gkey.skipsblanks
  1704.             || gkey.skipeblanks || gkey.month || gkey.numeric))
  1705.     insertkey (&gkey);
  1706.   reverse = gkey.reverse;
  1707.  
  1708.   if (nfiles == 0)
  1709.     {
  1710.       nfiles = 1;
  1711.       files = −
  1712.     }
  1713.  
  1714.   if (checkonly)
  1715.     exit (check (files, nfiles) != 0);
  1716.  
  1717.   if (strcmp (outfile, "-"))
  1718.     {
  1719.       for (i = 0; i < nfiles; ++i)
  1720.     if (!strcmp (outfile, files[i]))
  1721.       break;
  1722.       if (i == nfiles)
  1723.     ofp = xfopen (outfile, "w");
  1724.       else
  1725.     {
  1726.       char buf[8192];
  1727.       FILE *fp = xfopen (outfile, "r");
  1728.       int cc;
  1729.  
  1730.       tmp = tempname ();
  1731.       ofp = xfopen (tmp, "w");
  1732.       while ((cc = fread (buf, 1, sizeof buf, fp)) > 0)
  1733.         xfwrite (buf, 1, cc, ofp);
  1734.       if (ferror (fp))
  1735.         {
  1736.           error (0, errno, "%s", outfile);
  1737.           cleanup ();
  1738.           exit (2);
  1739.         }
  1740.       xfclose (ofp);
  1741.       xfclose (fp);
  1742.       files[i] = tmp;
  1743.       ofp = xfopen (outfile, "w");
  1744.     }
  1745.     }
  1746.   else
  1747.     ofp = stdout;
  1748.  
  1749.   if (mergeonly)
  1750.     merge (files, nfiles, ofp);
  1751.   else
  1752.     sort (files, nfiles, ofp);
  1753.   cleanup ();
  1754.  
  1755.   /* If we wait for the implicit flush on exit, and the parent process
  1756.      has closed stdout (e.g., exec >&- in a shell), then the output file
  1757.      winds up empty.  I don't understand why.  This is under SunOS,
  1758.      Solaris, Ultrix, and Irix.  This premature fflush makes the output
  1759.      reappear. --karl@cs.umb.edu  */
  1760.   if (fflush (ofp) < 0)
  1761.     error (1, errno, "fflush", outfile);
  1762.  
  1763.   if (have_read_stdin && fclose (stdin) == EOF)
  1764.     error (1, errno, "-");
  1765.   if (ferror (stdout) || fclose (stdout) == EOF)
  1766.     error (1, errno, "write error");
  1767.  
  1768.   exit (0);
  1769. }
  1770.  
  1771. static void
  1772. usage ()
  1773. {
  1774.   fprintf (stderr, "\
  1775. Usage: %s [-cmus] [-t separator] [-o output-file] [-T tempdir] [-bdfiMnr]\n\
  1776.        [+POS1 [-POS2]] [-k POS1[,POS2]] [file...]\n",
  1777.        program_name);
  1778.   exit (2);
  1779. }
  1780.